/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcUploadProofActivity.java
 *   @Date: 19-1-31 上午11:39
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.otc.adapter.OtcUploadImgAdapter;
import io.bhex.app.otc.presenter.OtcUploadProofPresenter;
import io.bhex.app.utils.FileTools;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.utils.crop.ImgPickHandler;
import io.bhex.baselib.utils.crop.ImgPickHelper;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.otc.bean.OtcOrderInfoResponse;
import io.bhex.sdk.otc.bean.OtcUploadImgResponse;
import pub.devrel.easypermissions.EasyPermissions;

public class OtcUploadProofActivity extends BaseActivity<OtcUploadProofPresenter,OtcUploadProofPresenter.OtcUploadProofUI> implements OtcUploadProofPresenter.OtcUploadProofUI, View.OnClickListener,EasyPermissions.PermissionCallbacks {
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x0;
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 0x2;
    private TopBar topBar;
    private OtcOrderInfoResponse orderInfo;
    private EditText appealReason;
    private RecyclerView recyclerView;
    private List<String> proofList = new ArrayList<>();
    private OtcUploadImgAdapter uploadAdapter;
    private String[] selectPhotoWayArray;
    private AlertView selectPhotoAlert;

    @Override
    protected int getContentView() {
        return R.layout.activity_otc_upload_proof_layout;
    }

    @Override
    protected OtcUploadProofPresenter createPresenter() {
        return new OtcUploadProofPresenter();
    }

    @Override
    protected OtcUploadProofPresenter.OtcUploadProofUI getUI() {
        return this;
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void initView() {
        super.initView();
        selectPhotoWayArray = new String[]{getString(R.string.string_take_photo),getString(R.string.string_gallery)};
        Intent intent = getIntent();
        if (intent != null) {
           orderInfo =(OtcOrderInfoResponse)intent.getSerializableExtra("order");
        }
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (orderInfo != null) {
                    IntentUtils.goOtcHistoryProof(OtcUploadProofActivity.this,orderInfo);
                }
            }
        });
        appealReason = viewFinder.editText(R.id.appealReason);
        recyclerView = viewFinder.find(R.id.recyclerView);

        proofList.add("+");
        showProofImgList(proofList);
    }

    private void showProofImgList(List<String> proofList) {
        if (uploadAdapter != null) {
            uploadAdapter.setNewData(proofList);
        }else{
            uploadAdapter = new OtcUploadImgAdapter(proofList);
            uploadAdapter.setEnableLoadMore(false);
            recyclerView.setLayoutManager(new GridLayoutManager(this,3));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            uploadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId()==R.id.itemImg) {
                        if (orderInfo != null) {
                            if (OtcUploadProofActivity.this.proofList.size()>6) {
                                ToastUtils.showShort(getString(R.string.string_hint_upload_up_to_six_pictures));
                                return;
                            }
                            showSelectPhoto();
                        }
                    }
                }
            });
            uploadAdapter.isFirstOnly(false);
            recyclerView.setAdapter(uploadAdapter);
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.btnSubmit).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnSubmit:
                String reason = appealReason.getText().toString();
                if (TextUtils.isEmpty(reason)) {
                    ToastUtils.showShort(getString(R.string.string_input_appeal_reason));
                    return;
                }
                if (proofList.size()<1) {
                    ToastUtils.showShort(getString(R.string.string_upload_proof_please));
                    return;
                }
                if (orderInfo != null) {
                    getPresenter().submitProof(orderInfo,reason,proofList);
                }

                break;
        }
    }


    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImgPickHelper.getInstance().handleResult(this, requestCode, resultCode, data);
    }

    /**
     * 选择图片
     */
    private void showSelectPhoto() {
        if(selectPhotoAlert != null && selectPhotoAlert.isShowing())
            return;
        selectPhotoAlert = new AlertView(null, null, getString(R.string.string_cancel), null, selectPhotoWayArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position==0){
                    //拍照
                    startSelectImage(true);
                }else{
                    //从相册选择
                    startSelectImage(false);
                }
            }
        });
        selectPhotoAlert.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
            }
        });
        selectPhotoAlert.show();
    }

    private void startSelectImage(boolean bCamera){
//        ImgPickHelper.getInstance().clearCachedCropFile(AuthenticateSubmitActivity.this);
        ImgPickHelper.getInstance().registeHandler(new ImgPickHandler() {

            @Override
            public void onSuccess(Uri uri) {
                uploadImage(uri);
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFailed(String message) {


            }
        });
        ImgPickHelper.getInstance().needCrop(false);
        if (bCamera) {
            String[] perms = {Manifest.permission.CAMERA};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), CAMERA_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goCamera(this);
            }

            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goCamera(getActivity());
            }*/

        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goGallery(this);
            }
            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goGallery(getActivity());
            }*/
        }

    }

    private void uploadImage(final Uri fromUri) {
        if (fromUri == null)
            return;
        if (FileTools.fileIsExists(fromUri.getPath())) {
            if (orderInfo != null) {
                String orderId = orderInfo.getId();
                getPresenter().uploadImage(orderId,fromUri.getPath(), new SimpleResponseListener<OtcUploadImgResponse>() {

                    @Override
                    public void onBefore() {
                        super.onBefore();
                        getUI().showProgressDialog("", getString(R.string.string_uploading));
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        getUI().dismissProgressDialog();
                    }

                    @Override
                    public void onSuccess(OtcUploadImgResponse response) {
                        super.onSuccess(response);
                        if (CodeUtils.isSuccess(response, true)) {
                            String photoUrl = response.getUrl();
                            if (proofList.size()>0) {
                                proofList.add(proofList.size()-1,photoUrl);
                            }else{
                                proofList.add(photoUrl);
                            }
                            showProofImgList(proofList);
                            ToastUtils.showLong(OtcUploadProofActivity.this, getString(R.string.string_upload_success));

                        }
                    }

                    @Override
                    public void onError(Throwable error) {
                        ToastUtils.showLong(OtcUploadProofActivity.this, getString(R.string.string_upload_failed));
                    }

                });
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        requestCodeQRCodePermissions();
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE){
            //takingPicture();
            ImgPickHelper.getInstance().goCamera(this);
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //mSourceIntent = ImageUtils.choosePicture();
            //startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
            ImgPickHelper.getInstance().goGallery(this);
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ImgPickHelper.getInstance().unregistHandler();
    }
}
